#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8888
#define BUFFER_SIZE 1024

void send_message(int sockfd,const char* message);
void handle_register(int sockfd);
void handle_login(int sockfd);


int main() 
{
    // 创建客户端套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) 
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // 连接服务器
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    server_addr.sin_port = htons(SERVER_PORT);

    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) 
    {
        perror("connect");
        exit(EXIT_FAILURE);
    }
    
	printf("Connected to server!\n");
	
	char buffer;
	printf("Enter 'l' to login or 'r' to register and login:");
	scanf("%c",buffer);
	if(buffer == 'l')
	{
		handle_login(sockfd);
	}
	else if(buffer == 'r')
	{
		handle_register(sockfd);
	}	
    // 与服务器进行交互
    /*while (1) 
    {
        // 1. 获取用户输入并发送给服务器
        // 2. 接收服务器返回的消息并显示
    }*/

    close(sockfd);
    return 0;
}


void handle_register(int sockfd)
{
	char username[32];
	char password[32];
	char buffer[32];
	char choice = "R";
	send(sockfd, &choice, sizeof(choice), 0);
	
	re_register:
	printf("Enter your username:");
	scanf("%s",username);
	send(sockfd, username, sizeof(username),0);
	printf("Enter your password:");
	scanf("%s",password);
	send(sockfd, password, sizeof(password),0);
	
	read(sockfd,buffer,sizeof(buffer));
	if (strcmp(buffer,"The username is already in use!") == 0)
	{
		printf("The username is already in use!Please re-enter\n");
		goto re_register;
	}
	else if(strcmp(buffer,"register_success") == 0)
	{
		printf("Registration successful!\nAutomatically logged in!\n");
	}
	else
	{
		printf("Registration failed.\n");
	}
}

void handle_login(int sockfd)
{
	char username[32];
	char password[32];
	char buffer[128];
	char choice = "L";
	
	send(sockfd, &choice, sizeof(choice), 0);
	
	printf("Enter your username:");
	scanf("%s",username);
	send(sockfd, username, sizeof(username),0);
	
	printf("Enter your password:");
	scanf("%s",password);
	send(sockfd, password, sizeof(password),0);	
	
	read(sockfd,buffer,sizeof(buffer));
	if(strcmp(buffer,"login_success") == 0)
	{
		printf("Login successful!\n");
	}
	else
	{
		printf("Login failed.\n");
	}	
}

